package com.gss.armory.web;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.hibernate.annotations.Proxy;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.gss.armory.domain.BusinessUnitTypeDTO;
import com.gss.armory.domain.CompanyDetailsDTO;
import com.gss.armory.domain.DepartmentDetailsDTO;
import com.gss.armory.domain.DocumentCategoryDTO;
import com.gss.armory.domain.DocumentSubCategory;
import com.gss.armory.domain.DocumentTypeDTO;
import com.gss.armory.domain.LocationDetailsDTO;
import com.gss.armory.form.DepartmentForm;
import com.gss.armory.form.DocumentCategoryForm;
import com.gss.armory.form.LocationForm;
import com.gss.armory.form.LocationMasterForm;
import com.gss.armory.form.SuperFicialRolesMappingForm;
import com.gss.armory.form.UploadLocationForm;
import com.gss.armory.form.UserDetailForm;
import com.gss.armory.form.UserSearchForm;
import com.gss.armory.persistence.CommonDAO;
import com.gss.armory.service.AdminService;
import com.gss.armory.service.ProcessDocumentService;
import com.gss.armory.service.WorkFlowService;
import com.gss.armory.util.BootUpLoader;
import com.gss.armory.validator.UserDetailFormValidator;
import com.gss.common.util.ApplicationConstants;
import com.gss.common.util.ApplicationMaps;
import com.gss.common.util.ApplicationUtilities;
import com.gss.security.domain.LocationMasterDTO;
import com.gss.security.domain.RoleDetailsDTO;
import com.gss.security.domain.SaveDataInWFTable;
import com.gss.security.domain.UserDetailsDTO;
import com.gss.security.domain.UserRoleMappingDTO;
import com.gss.security.service.AuthenticationService;
import com.gss.security.web.AuthenticationController;

@Controller
public class AdministrativeController {
	private Logger logger = Logger.getLogger(AdministrativeController.class);

	@Autowired
	AdminService adminService;

	@Autowired
	CommonDAO commonDao;

	@Autowired
	BootUpLoader bootUpLoader;
	
	@Autowired
	UserDetailFormValidator userDetailFormValidator;

	@Autowired
	WorkFlowService flowService;
	
	@Autowired
	ProcessDocumentService processDocumentService;

	@Autowired
	AuthenticationService authenticationService;
	
	@Value("#{dmsProp['enableAddAdminModule']}")
	String enableAddAdminModule;
	@Value("#{dmsProp['enableEditAdminModule']}")
	String enableEditAdminModule;
	@Value("#{dmsProp['enableViewAdminModule']}")
	String enableViewAdminModule;
	@Value("#{dmsProp['enableDeleteAdminmodule']}")
	String enableDeleteAdminmodule;
	
	
	//welcome page
	@RequestMapping(value = "/welcomeMe.htm")
	public ModelAndView showWelcomePage() {
		ModelAndView mav = new ModelAndView("admin/welcomeAdmin");
		
		mav.addObject("enableAddAdminModule" , enableAddAdminModule);
		mav.addObject("enableEditAdminModule" , enableEditAdminModule);
		mav.addObject("enableViewAdminModule" , enableViewAdminModule);
		mav.addObject("enableDeleteAdminmodule" , enableDeleteAdminmodule);
		
		mav.addObject("armoryMasterData", ApplicationMaps.ARMORY_MASTER_DATA);
		return mav;
	}

	
	//company
	@RequestMapping("/addCompanyPage")
	public ModelAndView addCompanyPage() {
		ModelAndView mav = new ModelAndView("admin/addCompany");
		
		CompanyDetailsDTO companyDetailsDTO = new CompanyDetailsDTO();
		LocationMasterDTO locationMasterDTOs = new LocationMasterDTO();
		Set<String> stateSet = new HashSet<String>();
		
		List<LocationMasterDTO> locationMasterDTO = adminService.loadLocationDetails(locationMasterDTOs);
		for (LocationMasterDTO locationMasterDTO2 : locationMasterDTO) {
			stateSet.add(locationMasterDTO2.getState());
		}
				
		List<CompanyDetailsDTO> parentCompaniesList = adminService.loadAllParentCompanies(companyDetailsDTO);
		
		mav.addObject("parentCompaniesList", parentCompaniesList);
		mav.addObject("companyDetailsDTO", companyDetailsDTO);
		mav.addObject("stateSet", stateSet);
		mav.addObject("formState", ApplicationConstants.FORM_NEW);
		
		return mav;
	}
	
	@RequestMapping("/saveCompany") 
	public ModelAndView saveCompany(@Valid CompanyDetailsDTO companyDetailsDTO,BindingResult bindingResult){
		ModelAndView mav = new ModelAndView("admin/addCompany");
		
		boolean errorExists = false;
		int errorCount = 0;
		
		List<LocationMasterDTO> locationMasterDTO = adminService.loadLocationDetails(new LocationMasterDTO());
		List<CompanyDetailsDTO> parentCompaniesList = adminService.loadAllParentCompanies(new CompanyDetailsDTO());
		Set<String> stateSet = new HashSet<String>();
		
		for (LocationMasterDTO locationMasterDTO2 : locationMasterDTO) {
			stateSet.add(locationMasterDTO2.getState());
		}
		
		if(ApplicationMaps.COMPANY_NAME_COMPANY_CODE_MAP.containsKey((companyDetailsDTO.getCdName()).trim())){
			bindingResult.rejectValue("cdName", "duplicateName", new Object[] {"Company", companyDetailsDTO.getCdName()}, "defaultMessageField");
			errorExists = true;
			errorCount++;
		}
		if(ApplicationMaps.COMPANY_NAME_COMPANY_CODE_MAP.containsValue((companyDetailsDTO.getCdCode()).trim())){
			bindingResult.rejectValue("cdCode", "duplicateCode", new Object[] {"Company", companyDetailsDTO.getCdCode()}, "defaultMessageField");
			errorExists = true;
			errorCount++;
		}
		if(ApplicationUtilities.checkIfNullOrBlank(companyDetailsDTO.getCompanyType())) {
			bindingResult.rejectValue("companyType", "companyTypeError", "defaultMessageRadio");
			errorExists = true;
			errorCount++;
		}
		
		if(bindingResult.getErrorCount() > 0){
			mav.addObject("errorCount", errorCount);
			mav.addObject("formState", ApplicationConstants.FORM_OLD);
			mav.addObject("companyDetailsDTO", companyDetailsDTO);
		}
		
		if(!errorExists && errorCount <= 0){
			if(companyDetailsDTO.getCompanyType().equalsIgnoreCase("GroupHead"))
				companyDetailsDTO.setChild(false);
			else
				companyDetailsDTO.setChild(true);
			companyDetailsDTO.setAddress(companyDetailsDTO.getAddress().trim());
			companyDetailsDTO.setCdCode(companyDetailsDTO.getCdCode().trim());
			companyDetailsDTO.setCdName(companyDetailsDTO.getCdName().trim());
			
			boolean result= adminService.saveCompany(companyDetailsDTO);
			logger.debug("Result Of saving company with name " + companyDetailsDTO.getCdName() + " is " + result);
			if(result) {
				mav.addObject("formState", ApplicationConstants.FORM_NEW);
				mav.addObject("successMessage","Company with name " + companyDetailsDTO.getCdName() 
						+ "(" + companyDetailsDTO.getCdCode() + ") is created successfully.");
			}
			mav.addObject("companyDetailsDTO", new CompanyDetailsDTO());
		}
		mav.addObject("stateSet", stateSet);
		mav.addObject("parentCompaniesList", parentCompaniesList);
			
		return mav;
	}
	
	@RequestMapping("/viewCompany.htm")
	public ModelAndView viewCompany() {
		ModelAndView mav = new ModelAndView("admin/viewCompany");
		
		mav.addObject("companyMap", ApplicationMaps.COMPANYID_COMPANY_MAP);
		mav.addObject("size", ApplicationMaps.COMPANYID_COMPANY_MAP.size());
			
		return mav;
	}	
	
	@RequestMapping("/editCompany")
	public ModelAndView editCompany() {
		
		ModelAndView modelAndView = new ModelAndView("admin/editCompany");
		
		CompanyDetailsDTO companyDetailsDTO = new CompanyDetailsDTO();
		LocationMasterDTO locationMasterDTOs = new LocationMasterDTO();
		
		List<LocationMasterDTO> locationMasterDTO = adminService.loadLocationDetails(locationMasterDTOs);
		Set<String> stateSet = new HashSet<String>();
		for (LocationMasterDTO locationMasterDTO2 : locationMasterDTO) {
			stateSet.add(locationMasterDTO2.getState());
		}
				
		List<CompanyDetailsDTO> parentCompaniesList = adminService.loadAllParentCompanies(companyDetailsDTO);
		
		modelAndView.addObject("parentCompaniesList", parentCompaniesList);
		modelAndView.addObject("stateSet", stateSet);
		modelAndView.addObject("companyMap", ApplicationMaps.COMPANYID_COMPANY_MAP);
		modelAndView.addObject("companyDetailsDTO", companyDetailsDTO);
		
		return modelAndView;
	}
	
	
	@RequestMapping("/saveCompanyNewDetails")
	public ModelAndView saveCompanyNewDetails(@Valid CompanyDetailsDTO companyDetailsDTO, BindingResult bindingResult){
		
		ModelAndView modelAndView = new ModelAndView("admin/editCompany");
		boolean errorExists = false;
		int errorCount = 0;

		LocationMasterDTO locationMasterDTOs = new LocationMasterDTO();
		List<LocationMasterDTO> locationMasterDTO = adminService.loadLocationDetails(locationMasterDTOs);
		List<CompanyDetailsDTO> parentCompaniesList = adminService.loadAllParentCompanies(companyDetailsDTO);
		Set<String> stateSet = new HashSet<String>();
		for (LocationMasterDTO locationMasterDTO2 : locationMasterDTO) {
			stateSet.add(locationMasterDTO2.getState());
		}
		
		if(ApplicationUtilities.checkIfNullOrBlank(companyDetailsDTO.getCdName().trim())){
			bindingResult.rejectValue("cdName", "fieldBlank", "defaultMessageField");
			errorExists = true;
			errorCount++;
		}
		if(ApplicationMaps.COMPANY_NAME_COMPANY_CODE_MAP.containsKey((companyDetailsDTO.getCdName()).trim())){
			bindingResult.rejectValue("cdName", "duplicateName", new Object[] {"Company", companyDetailsDTO.getCdName()}, "defaultMessageField");
			errorExists = true;
			errorCount++;
		}
		if(ApplicationUtilities.checkIfNullOrBlank(companyDetailsDTO.getAddress().trim())) {
			bindingResult.rejectValue("address", "fieldBlank", "defaultMessageField");
			errorExists = true;
			errorCount++;
		}
		if(ApplicationUtilities.checkIfNullOrBlank(companyDetailsDTO.getCdState()) && 
				companyDetailsDTO.getCdState().equalsIgnoreCase("0")) {
			bindingResult.rejectValue("cdState", "emptySelect", "defaultMessageSelect");
			errorExists = true;
			errorCount++;
		}

		
		if(bindingResult.getErrorCount() > 0) {
			modelAndView.addObject("errorCount", errorCount);
//			modelAndView.addObject("formState", ApplicationConstants.FORM_OLD);
			modelAndView.addObject("companyDetailsDTO", companyDetailsDTO);
		}
		
		if(!errorExists && errorCount <= 0){
			if(companyDetailsDTO.getCompanyType().equalsIgnoreCase("GroupHead"))
				companyDetailsDTO.setChild(false);
			else
				companyDetailsDTO.setChild(true);
			
			companyDetailsDTO.setAddress(companyDetailsDTO.getAddress().trim());
			companyDetailsDTO.setCdCode(companyDetailsDTO.getCdCode().trim());
			companyDetailsDTO.setCdName(companyDetailsDTO.getCdName().trim());
			
			boolean resultOfSave =  adminService.saveCompanyEditDetails(companyDetailsDTO);
			modelAndView.addObject("resultOfSave", resultOfSave);
			modelAndView.addObject("errorCount", 0);
		}	
		
		modelAndView.addObject("companyMap", ApplicationMaps.COMPANYID_COMPANY_MAP);
		modelAndView.addObject("companyDetailsDTO", companyDetailsDTO);
		modelAndView.addObject("stateSet", stateSet);
		modelAndView.addObject("parentCompaniesList", parentCompaniesList);
		
		return modelAndView;
		
	}
	
	
	
	
	@RequestMapping("/searchUserPage")
	public ModelAndView searchUserPage() {
		ModelAndView mav = new ModelAndView("admin/searchUser");
		return mav;
	}

	@RequestMapping("/mapRoleToUser")
	public ModelAndView mapRoleToUser(@RequestParam("userIdResult") String userId) {
		ModelAndView mav = new ModelAndView();
		
		if (!userId.equals("") && ApplicationMaps.USERID_USERNAME_MAP.containsKey(userId)) {
			UserRoleMappingDTO userRoleMappingDTO = new UserRoleMappingDTO();
			UserDetailsDTO userDetailsDTO = authenticationService.getUserForProvidedUserId(userId);
			logger.debug("inside administrative controller: method(mapRoleToUser): usrdetailsdto object for user id: " + userId 
					+ " is: " + userDetailsDTO.toString());
			
			if (null != userDetailsDTO) {
				List<GrantedAuthority> authorities = (List<GrantedAuthority>) userDetailsDTO.getAuthorities();
				List<String> list = new ArrayList<String>();
				List<RoleDetailsDTO> differentAppRoleList = new ArrayList<RoleDetailsDTO>();
				for (GrantedAuthority authority : authorities) {
					RoleDetailsDTO detailsDTO1 = (RoleDetailsDTO) authority;
					list.add(detailsDTO1.getRoleId());
					differentAppRoleList.add(detailsDTO1);
				}
				
				String[] role = new String[list.toArray().length];
				for (int i = 0; i < list.toArray().length; i++) {
					role[i] = list.toArray()[i].toString();
				}
				
				List<RoleDetailsDTO> roleList = authenticationService.loadCompleteRoleList();
				List<RoleDetailsDTO> newRoleList = new ArrayList<RoleDetailsDTO>();
				
				for (RoleDetailsDTO roleDetailsDTO : roleList) {
					if(!roleDetailsDTO.getRoleId().equalsIgnoreCase(ApplicationConstants.SUPER_ADMIN_ROLE))
						newRoleList.add(roleDetailsDTO);
				}
				
				userRoleMappingDTO.setRoles(role);
				mav.addObject("roleList", newRoleList);
				mav.addObject("userName", userDetailsDTO.getUsername());
				mav.addObject("userDisplayName",userDetailsDTO.getUserDisplayName());
				mav.addObject("userRoleMapping", userRoleMappingDTO);
				mav.addObject("appId", ApplicationConstants.APP_ID);
				mav.addObject("differentAppRoleList", differentAppRoleList);
				mav.setViewName("admin/roleMapping");
			}
			/*else{
				mav.addObject("result", true);
				mav.setViewName("admin/searchUser");
			}*/
		}
		else {
			mav.addObject("result", true);
			mav.setViewName("admin/searchUser");
		}
		return mav;
	}
	
	@RequestMapping("/assignRole")
	public ModelAndView assignRole(UserRoleMappingDTO detailsDTO) {
		ModelAndView mav = new ModelAndView();
		if (authenticationService.assignRoleToNewUser(detailsDTO)) {
			bootUpLoader.loadSuperficialRoleMappingData();
			mav.setViewName("admin/success");
			return mav;
		} else {
			mav.setViewName("admin/roleMapping");
			return mav;
		}
	}

	@RequestMapping("/addDepartmentPage")
	public ModelAndView addDepartmentPage() {

		ModelAndView mav = new ModelAndView("admin/addDepartment");
		DepartmentForm departmentForm = new DepartmentForm();
		mav.addObject("departmentForm", departmentForm);
		return mav;
	}
	
	@RequestMapping("/addLocationMaster")
	public ModelAndView openLocationMaster(){
		ModelAndView modelAndView = new ModelAndView("admin/addNewLocationMaster");
		LocationMasterDTO locationMasterDTO = new LocationMasterDTO();
		
		Set<String> stateSet = new HashSet<String>();
		
		for (LocationMasterDTO locationMasterDTO2 : (List<LocationMasterDTO>)adminService.loadLocationDetails(locationMasterDTO)) {
			stateSet.add(locationMasterDTO2.getState());
		}
		LocationMasterForm locationMasterForm = new LocationMasterForm();
		
		modelAndView.addObject("stateSet", stateSet);
		modelAndView.addObject("locationMasterForm", locationMasterForm);
		modelAndView.addObject("uploadLocationForm", new UploadLocationForm());
	
		return modelAndView;
	}
	
	@RequestMapping("/uploadLocationExcel")
	public ModelAndView uploadLocationExcel(@ModelAttribute UploadLocationForm uploadLocationForm, HttpServletResponse httpServletResponse){
		
		ModelAndView modelAndView = new ModelAndView("admin/fileUploadResult");
		MultipartFile inputFile = uploadLocationForm.getInputFile();
		List<LocationMasterDTO> locationMasterList = new ArrayList<LocationMasterDTO>();
		int rowCounter = 0;
		int commitedCounter = 0;
		StringBuffer responseBuffer = new StringBuffer();
		
		logger.debug("Content Type: " + inputFile.getContentType() + " ***** Original File Name: " + inputFile.getOriginalFilename());
		XSSFWorkbook inputWorkbook = null;
		XSSFSheet locationSheet = null;
		
		try{
			inputWorkbook = new XSSFWorkbook(inputFile.getInputStream());
			logger.debug("Number of sheets in inputFile: " + inputWorkbook.getNumberOfSheets());
			
			locationSheet = inputWorkbook.getSheetAt(0);
			
			if(!(inputWorkbook.getNumberOfSheets() == 0)){
				locationSheet = inputWorkbook.getSheetAt(0);
			}
			else{
				httpServletResponse.getWriter().write("Input excel file is not having any sheets");
			}
			
			XSSFRow headerRow = locationSheet.getRow(0);
			Iterator<Cell> iterator = headerRow.cellIterator();
			int columnCount = 0;
			while (iterator.hasNext()) {
				System.out.print(iterator.next().getStringCellValue()+ " , ");
				columnCount++;
			}
			logger.debug("Number of columns in sheet: " + columnCount);
			
			Iterator<Row> rowIterator = locationSheet.rowIterator();
			rowIterator.next();				// skip header row
			XSSFRow transactionRow = null;
			while(rowIterator.hasNext()){
				transactionRow = (XSSFRow) rowIterator.next();
				locationMasterList.add(printRowContent(transactionRow, columnCount));
				rowCounter++;
			}
			responseBuffer.append("Number of rows read from excel: " +rowCounter + "\n");
			logger.debug("number of rows read from excel: " + rowCounter);
			
			try {
				commitedCounter = commonDao.uploadLocationMasterData(locationMasterList);
				bootUpLoader.loadLocationMaster();
			} catch (Throwable e) {
				logger.error(e.getMessage(),e);
			}
		}
		catch(Exception e){
			logger.error(e.getMessage(),e);
		}
		
		inputWorkbook = null;
		responseBuffer.append("Number of rows added to database: " + commitedCounter + "\n");
		
		if(commitedCounter == rowCounter){
			responseBuffer.append("Upload Successful.");
		}else{
			responseBuffer.append("Upload Unsuccessful.");
		}
		modelAndView.addObject("responseMessage",responseBuffer.toString());
		modelAndView.setViewName("admin/fileUploadResult");
		return modelAndView;
	}
	
	private LocationMasterDTO printRowContent(XSSFRow row,int columnCount){
		LocationMasterDTO locationMasterDTO = new LocationMasterDTO();
		XSSFCell currentCell = null;
		
		for(int i =0; i < columnCount;i++){
			currentCell = row.getCell(i);
			try{
				if(null != currentCell && null != currentCell.getRawValue()) {
					switch (i) {
					case 1:
						locationMasterDTO.setCity(currentCell.toString());
						break;
					case 2:
						locationMasterDTO.setDistrict(currentCell.toString());
						break;
					case 3:
						locationMasterDTO.setState(currentCell.getStringCellValue());
						break;
					default:
						logger.debug("value at column index " + i + " ignored , ");
						break;
					}
				}
			}
			catch (Exception e) {
				logger.error("ERROR IN UPLOADING EXCEL : -- " + currentCell.getCellType() + e.getMessage(), e);
			}
		}
		
		return locationMasterDTO;
	}
	
	@RequestMapping("/saveLocationMasterDetails")
	public ModelAndView saveLocationMasterDetails(@ModelAttribute LocationMasterForm locationMasterForm,BindingResult bindingResult){
		ModelAndView modelAndView = new ModelAndView("admin/addNewLocationMaster");

		LocationMasterDTO locationMasterDTO = new LocationMasterDTO();
		Set<String> stateSet = new HashSet<String>();
		for (LocationMasterDTO locationMasterDTO2 : (List<LocationMasterDTO>)adminService.loadLocationDetails(locationMasterDTO)) {
			stateSet.add(locationMasterDTO2.getState());
		}
		logger.error("ERROR--- " + bindingResult.getAllErrors());
		
		FieldError fieldError;
		
		if(null == locationMasterForm.getNewState() || locationMasterForm.getNewState().equalsIgnoreCase("")){
			if(locationMasterForm.getState().equalsIgnoreCase("-1")){
				fieldError = new FieldError("locationMasterForm", "state", "The field cannot be left blank.");
				bindingResult.addError(fieldError);
			}
		}
		if(null == locationMasterForm.getNewDistrict() || locationMasterForm.getNewDistrict().equalsIgnoreCase("")){
			if(locationMasterForm.getDistrict().equalsIgnoreCase("-1")){
				fieldError = new FieldError("locationMasterForm", "district", "The field cannot be left blank.");
				bindingResult.addError(fieldError);
			}
		}
		if(null == locationMasterForm.getNewCity() || locationMasterForm.getNewCity().equalsIgnoreCase("")){
			if(locationMasterForm.getCity().equalsIgnoreCase("-1")){
				fieldError = new FieldError("locationMasterForm", "city", "The field cannot be left blank.");
				bindingResult.addError(fieldError);
			}
		}
		
		if(bindingResult.getErrorCount()>0){
			modelAndView.addObject("locationMasterForm", locationMasterForm);
		}
		else{
			if(locationMasterForm.getState().equalsIgnoreCase("-1")){
				locationMasterDTO.setState(locationMasterForm.getNewState());
			}
			else{
				locationMasterDTO.setState(locationMasterForm.getState());
			}
			if(locationMasterForm.getDistrict().equalsIgnoreCase("-1")){
				locationMasterDTO.setDistrict(locationMasterForm.getNewDistrict());
			}
			else{
				locationMasterDTO.setDistrict(locationMasterForm.getDistrict());
			}
			if(locationMasterForm.getCity().equalsIgnoreCase("-1")){
				locationMasterDTO.setCity(locationMasterForm.getNewCity());
			}
			else{
				locationMasterDTO.setCity(locationMasterForm.getCity());
			}
			int errorCount = bindingResult.getErrorCount();
			errorCount = 0;
			logger.debug("ERROR COUNT" + errorCount);
	
			boolean result =  adminService.saveLocationMasterDetails(locationMasterDTO);
			logger.debug("Result of entry: " + result);
			
			modelAndView.addObject("errorCount", errorCount);
			modelAndView.addObject("resultOfEntry", result);
			
		}
		modelAndView.addObject("stateSet", stateSet);
		modelAndView.addObject("uploadLocationForm", new UploadLocationForm());
		
		return modelAndView;
	}

	@RequestMapping("/addUserPage")
	public ModelAndView addUserPage() {
		ModelAndView mav = new ModelAndView("admin/addNewUser");
		
		UserDetailForm userDetailForm = new UserDetailForm();
		/*ArrayList<LocationDetailsDTO> locationList = new ArrayList<LocationDetailsDTO>();
		locationList.addAll(ApplicationMaps.LOCID_LOC_MAP.values());
		*/
		mav.addObject("userDetailForm", userDetailForm);
		//mav.addObject("locationList", locationList);
		//mav.addObject("departmentMap", ApplicationMaps.DEPTID_DEPTSNAME_MAP);
		
		UserDetailsDTO userDetailsDTO = (UserDetailsDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if(ApplicationConstants.ALL_INT.equals(userDetailsDTO.getCdId())){
			mav.addObject("companyMap", ApplicationMaps.COMPANYID_COMPANY_MAP.values());
		}
		else{
			List<CompanyDetailsDTO> company = new ArrayList<CompanyDetailsDTO>();
			company.add(ApplicationMaps.COMPANYID_COMPANY_MAP.get(userDetailsDTO.getCdId()));
			mav.addObject("companyMap", company);
		}
		

		return mav;
	}

	@RequestMapping("/addDocSubCategoryPage")
	public ModelAndView addDocSubCategoryPage() {
		ModelAndView mav = new ModelAndView("admin/addNewDocSubCategory");
		DocumentSubCategory documentSubCategory = new DocumentSubCategory();
		mav.addObject("documentSubCategory", documentSubCategory);
		mav.addObject("docTypeMap", ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP);
		return mav;
	}

	@RequestMapping("/addBussinessUnitTypePage.htm")
	public ModelAndView addBusinessUnitTypePage() {
		ModelAndView mav = new ModelAndView("admin/addBussinessUnitType");
		BusinessUnitTypeDTO businessUnitTypeDTO = new BusinessUnitTypeDTO();
		logger.debug("BUSINESS DETAILS DTO OBJECT" + businessUnitTypeDTO);
		mav.addObject("businessUnitTypeDTO", businessUnitTypeDTO);
		return mav;
	}

	@RequestMapping("/docTypePage")
	public ModelAndView addDoctTypePage() {
		ModelAndView mav = new ModelAndView("admin/createDocumentType");
		DocumentTypeDTO documentTypeDTO = new DocumentTypeDTO();
		mav.addObject("documentTypeDTO", documentTypeDTO);
		return mav;
	}

	@RequestMapping("/addDocCategoryPage")
	public ModelAndView addCategoryPage() {
		ModelAndView mav = new ModelAndView("admin/addDocumentCategory");
		DocumentCategoryForm documentCategoryForm = new DocumentCategoryForm();
		mav.addObject("documentCategoryForm", documentCategoryForm);
		ArrayList<DocumentTypeDTO> docTypeList = new ArrayList<DocumentTypeDTO>();
		docTypeList.addAll(ApplicationMaps.DOCUMENT_TYPE_ID_MAP.values());
		mav.addObject("docTypeList", docTypeList);
		return mav;
	}

	@RequestMapping("/addLocationPage")
	public ModelAndView addLocationPage() {
		ModelAndView mav = new ModelAndView("admin/addNewLocation");
		
		LocationForm locationForm = new LocationForm();
		
		
		ArrayList<BusinessUnitTypeDTO> bussinessUnitTypeList = (ArrayList<BusinessUnitTypeDTO>) adminService.loadAllBU();
	
		UserDetailsDTO userDetailsDTO = (UserDetailsDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if(ApplicationConstants.ALL_INT.equals(userDetailsDTO.getCdId())){
			ArrayList<CompanyDetailsDTO> companyList = new ArrayList<CompanyDetailsDTO>();
			companyList.addAll(ApplicationMaps.COMPANYID_COMPANY_MAP.values());
			mav.addObject("companyList", companyList);
//			mav.addObject("companyMap", ApplicationMaps.COMPANYID_COMPANY_MAP.values());
		}
		else{
			List<CompanyDetailsDTO> company = new ArrayList<CompanyDetailsDTO>();
			company.add(ApplicationMaps.COMPANYID_COMPANY_MAP.get(userDetailsDTO.getCdId()));
			mav.addObject("companyList", company);
		}
		
		mav.addObject("locationForm", locationForm);
		mav.addObject("bUList", bussinessUnitTypeList);
  		
		mav.addObject("departmentMap", ApplicationMaps.DEPTID_DEPTSNAME_MAP);
		return mav;
	}

	@RequestMapping("/saveUnitType")
	public ModelAndView saveUnitType(@Valid BusinessUnitTypeDTO businessUnitTypeDTO,BindingResult bindingResult)
	{
  
		businessUnitTypeDTO.setBuTypeCode(businessUnitTypeDTO.getBuTypeCode().trim());
		businessUnitTypeDTO.setBuTypeName(businessUnitTypeDTO.getBuTypeName().trim());
		ModelAndView mav = new ModelAndView("admin/addBussinessUnitType");
		if(bindingResult.hasErrors()){
			logger.debug(bindingResult.getErrorCount());
			mav.addObject("businessUnitTypeDTO", businessUnitTypeDTO);			
		} 
		else{
			
			int errorCount = bindingResult.getErrorCount();
			errorCount = 0;
	
			boolean result= adminService.saveUnitType(businessUnitTypeDTO);
			logger.debug("Result of save: " + result);
			
			mav.addObject("errorCount", errorCount);
			mav.addObject("resultOfEntry", result);
		}
		return mav;
	}
	
	@RequestMapping("/saveLocation")
	public ModelAndView saveLocation(@Valid LocationForm locationForm,
			BindingResult bindingResult){
			locationForm.setLdName(locationForm.getLdName().trim());
			locationForm.setLdCode(locationForm.getLdCode().trim());
			
 		ModelAndView mav = new ModelAndView("admin/addNewLocation");
 		ArrayList<CompanyDetailsDTO> companyList = new ArrayList<CompanyDetailsDTO>();
		companyList.addAll(ApplicationMaps.COMPANYID_COMPANY_MAP.values());
		logger.debug(locationForm.getLdType());
		ArrayList<BusinessUnitTypeDTO> bussinessUnitList = (ArrayList<BusinessUnitTypeDTO>) adminService.loadAllBU();
		mav.addObject("bUList", bussinessUnitList);
		mav.addObject("companyList", companyList);
		mav.addObject("departmentMap", ApplicationMaps.DEPTID_DEPTSNAME_MAP);
		
		FieldError fieldError = null;
		
		if(locationForm.getLdCompanyId().getCdId() == 0){
			fieldError = new FieldError("locationForm", "ldCompanyId.cdId" , "Please choose a company.");
			bindingResult.addError(fieldError);
		}
		if(locationForm.getLdType().equalsIgnoreCase("0")){
			fieldError = new FieldError("locationForm", "ldType" , "Please choose a business unit type.");
			bindingResult.addError(fieldError);
		}
		if(locationForm.getDdId().length == 0){
			fieldError = new FieldError("locationForm", "ddId" , "Please choose a department.");
			bindingResult.addError(fieldError);
		}
		
		if(bindingResult.getErrorCount()>0)
		{
  			for(FieldError error:bindingResult.getFieldErrors()){
				logger.debug(error.toString());
			}
			logger.debug(bindingResult.getErrorCount());
			mav.addObject("locationForm", locationForm);
			
		}
		else
		{		
			
			int errorCount = bindingResult.getErrorCount();
			errorCount = 0;
			logger.debug("ERROR COUNT" + errorCount);
	
			boolean result= adminService.saveLocation(locationForm);
			logger.debug("BOOLEAN" + result);
			
			mav.addObject("errorCount", errorCount);
			mav.addObject("resultOfEntry", result);
		}
		return mav;
	}

	
	@RequestMapping("/saveDepartment") 
	public ModelAndView saveDepartment(@Valid DepartmentForm departmentForm,BindingResult bindingResult)	
	{
  
		departmentForm.setDdName(departmentForm.getDdName().trim());
		departmentForm.setDdShortName(departmentForm.getDdShortName().trim());
		
		ModelAndView mav = new ModelAndView("admin/addDepartment");
  
		if(bindingResult.getErrorCount()>0)
		{
			mav.addObject("departmentForm", departmentForm);
		}
		
		else{
			
			int errorCount = bindingResult.getErrorCount();
			errorCount = 0;
			logger.debug("ERROR COUNT" + errorCount);
	
			boolean result= adminService.saveDepartment(departmentForm);
			logger.debug("BOOLEAN" + result);
			
			mav.addObject("errorCount", errorCount);
			mav.addObject("resultOfEntry", result);
		}
 		return mav;
 	}
	

	

	@RequestMapping("/saveUser")
	public ModelAndView saveUser(@Valid UserDetailForm userDetailForm,
			BindingResult bindingResult) throws IllegalAccessException, InvocationTargetException {
		
		userDetailForm.setUsername(userDetailForm.getUsername().trim());
		userDetailForm.setUserDisplayName(userDetailForm.getUserDisplayName().trim());
				
		ModelAndView mav = new ModelAndView();
		
		FieldError fieldError = null;
		
		if(ApplicationMaps.USERID_USERNAME_MAP.containsKey(userDetailForm.getUsername())){
			fieldError = new FieldError("userDetailForm", "username", "User Already Exists.");
			bindingResult.addError(fieldError);
		}
		if(userDetailForm.getCdId() == 0){
			fieldError = new FieldError("userDetailForm", "cdId", "Select Company from drop down.");
			bindingResult.addError(fieldError);
		}
		if(userDetailForm.getBuId() == 0){
			fieldError = new FieldError("userDetailForm", "locationId", "Select Business Unit from drop down.");
			bindingResult.addError(fieldError);
		}
		if(userDetailForm.getDeptId() == 0){
			fieldError = new FieldError("userDetailForm", "depttId", "Select Department from drop down.");
			bindingResult.addError(fieldError);
		}
			
		
		if (bindingResult.getErrorCount() > 0) {
			logger.debug("WHILE SAVING THE USER"+ bindingResult.getErrorCount());
			mav.setViewName("admin/addNewUser");
			mav.addObject("companyMap", ApplicationMaps.COMPANYID_COMPANY_MAP.values());
		}
		else{
			int errorCount = bindingResult.getErrorCount();
			errorCount = 0;
			logger.debug("ERROR COUNT: " + errorCount);
	
			boolean result= authenticationService.saveNewUser(userDetailForm);
			logger.debug("BOOLEAN" + result);
			if(result){
				List<RoleDetailsDTO> roleList = authenticationService.loadCompleteRoleList();
				
				List<RoleDetailsDTO> newRoleList = new ArrayList<RoleDetailsDTO>();
				for (RoleDetailsDTO roleDetailsDTO : roleList) {
					if(!roleDetailsDTO.getRoleId().equalsIgnoreCase(ApplicationConstants.SUPER_ADMIN_ROLE))
						newRoleList.add(roleDetailsDTO);
				}
			
				UserRoleMappingDTO userRoleMappingDTO = new UserRoleMappingDTO();
				mav.addObject("roleList", newRoleList);
				mav.addObject("userName", userDetailForm.getUsername());
				mav.addObject("userDisplayName",userDetailForm.getUserDisplayName());
				mav.addObject("userRoleMapping", userRoleMappingDTO);
				mav.setViewName("admin/roleMapping");
			}
			mav.addObject("errorCount", errorCount);
			mav.addObject("resultOfEntry", result);
			mav.addObject("userDetailForm", new UserDetailForm());
			mav.addObject("companyMap", ApplicationMaps.COMPANYID_COMPANY_MAP.values());
		}
	
		return mav;	
	}

	@RequestMapping("/saveDocType")
	public ModelAndView addDocType(@Valid DocumentTypeDTO documentTypeDTO, BindingResult bindingResult )
	{
		documentTypeDTO.setDtName(documentTypeDTO.getDtName().trim());
		documentTypeDTO.setDtCode(documentTypeDTO.getDtCode().trim());
		
		ModelAndView mav = new ModelAndView("admin/createDocumentType");
		if(bindingResult.getFieldErrorCount()>0){
			mav.addObject("documentTypeDTO", documentTypeDTO);
		} 
		else {

			int errorCount = bindingResult.getErrorCount();
			errorCount = 0;
			logger.debug("ERROR COUNT" + errorCount);
	
			boolean result= adminService.saveDocumentType(documentTypeDTO);
			logger.debug("BOOLEAN" + result);
			
			mav.addObject("errorCount", errorCount);
			mav.addObject("resultOfEntry", result);
			mav.addObject("userDetailForm", new UserDetailForm());

		}
		return mav;
	}

	@RequestMapping("/saveDocCategory")
	public ModelAndView addDocCategory(@Valid DocumentCategoryForm documentCategoryForm,BindingResult bindingResult)
	{
		documentCategoryForm.setDcName(documentCategoryForm.getDcName().trim());
		documentCategoryForm.setDcCode(documentCategoryForm.getDcCode().trim());
		
		ModelAndView mav = new ModelAndView("admin/addDocumentCategory");
		ArrayList<DocumentTypeDTO> docTypeList = new ArrayList<DocumentTypeDTO>();
		docTypeList.addAll(ApplicationMaps.DOCUMENT_TYPE_ID_MAP.values());
		mav.addObject("docTypeList", docTypeList);

		if(bindingResult.hasErrors()){
			mav.addObject("documentCategoryForm", documentCategoryForm);
		} 
		else{

			int errorCount = bindingResult.getErrorCount();
			errorCount = 0;
			logger.debug("ERROR COUNT" + errorCount);
	
			boolean result= adminService.saveDocumentCategory(documentCategoryForm);
			logger.debug("BOOLEAN" + result);
			
			mav.addObject("errorCount", errorCount);
			mav.addObject("resultOfEntry", result);
			mav.addObject("documentCategoryForm", new DocumentCategoryForm());
		}
		return mav;
	}
	
	@RequestMapping("/saveDocSubCategory")
	public ModelAndView saveDocSubCategory(@Valid DocumentSubCategory documentSubCategory,BindingResult bindingResult){
		
		documentSubCategory.setDscName(documentSubCategory.getDscName().trim());
		documentSubCategory.setDscCode(documentSubCategory.getDscCode().trim());
		ModelAndView mav = new ModelAndView("admin/addNewDocSubCategory");
		mav.addObject("docTypeMap",ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP);	
		if(bindingResult.hasErrors()){
			logger.error("ERROR: " + bindingResult.getAllErrors());
			mav.addObject("documentSubCategory", documentSubCategory);
		}
		else{
			int errorCount = bindingResult.getErrorCount();
			errorCount = 0;
	
			boolean result= adminService.saveDocumentsubCategory(documentSubCategory);
			logger.debug("BOOLEAN" + result);
			
			mav.addObject("errorCount", errorCount);
			mav.addObject("resultOfEntry", result);
			mav.addObject("documentSubCategory", new DocumentSubCategory());
		}
		return mav;
	}
	
	@RequestMapping("/viewBusinessUnitType")
	public ModelAndView viewBusinessUnitType() {

		ModelAndView mav = new ModelAndView("admin/viewBussinessUnitType");
		List<BusinessUnitTypeDTO> businessUnitList = adminService.loadAllBU();
		mav.addObject("businessUnitList", businessUnitList);
		mav.addObject("size", businessUnitList.size());
		return mav;
	}

	@RequestMapping("/viewLocation")
	public ModelAndView viewLocation() {
		ModelAndView mav = new ModelAndView("admin/viewLocation");
		UserDetailsDTO userDetailsDTO = (UserDetailsDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if(ApplicationConstants.ALL_INT.equals(userDetailsDTO.getCdId())) {
			mav.addObject("locationMap", ApplicationMaps.LOCID_LOC_MAP);
		}
		else{
			List<LocationDetailsDTO> buListAccToCompany = ApplicationMaps.COMPANY_LOC_MAP.get(userDetailsDTO.getCdId());
			HashMap<Long, LocationDetailsDTO> LOCATION_MAP_ADMIN = new HashMap<Long, LocationDetailsDTO>();
			for (LocationDetailsDTO locationDetailsDTO : buListAccToCompany) {
				LOCATION_MAP_ADMIN.put(locationDetailsDTO.getLdId(), locationDetailsDTO);
				mav.addObject("locationMap", LOCATION_MAP_ADMIN);				
			}
		}
		
		mav.addObject("size", ApplicationMaps.LOCID_LOC_MAP.size());
		return mav;
	}
	
	@RequestMapping("/editBusinessUnitDetails")
	public ModelAndView editBusinessUnitDetails(){
		ModelAndView modelAndView = new ModelAndView("admin/editBusinessUnit");
		
		LocationForm locationForm = new LocationForm();
		
//		ArrayList<CompanyDetailsDTO> companyList = new ArrayList<CompanyDetailsDTO>();
//		companyList.addAll(ApplicationMaps.COMPANYID_COMPANY_MAP.values());
		ArrayList<BusinessUnitTypeDTO> bussinessUnitTypeList = (ArrayList<BusinessUnitTypeDTO>) adminService.loadAllBU();
				
		UserDetailsDTO userDetailsDTO = (UserDetailsDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if(ApplicationConstants.ALL_INT.equals(userDetailsDTO.getCdId())){
			ArrayList<CompanyDetailsDTO> companyList = new ArrayList<CompanyDetailsDTO>();
			companyList.addAll(ApplicationMaps.COMPANYID_COMPANY_MAP.values());
			modelAndView.addObject("companyList", companyList);
			modelAndView.addObject("locationMap", ApplicationMaps.LOCID_LOC_MAP);
		}
		else{
			List<CompanyDetailsDTO> company = new ArrayList<CompanyDetailsDTO>();
			company.add(ApplicationMaps.COMPANYID_COMPANY_MAP.get(userDetailsDTO.getCdId()));
			modelAndView.addObject("companyList", company);
			
			List<LocationDetailsDTO> buListAccToCompany = ApplicationMaps.COMPANY_LOC_MAP.get(userDetailsDTO.getCdId());
			HashMap<Long, LocationDetailsDTO> LOCATION_MAP_ADMIN = new HashMap<Long, LocationDetailsDTO>();
			for (LocationDetailsDTO locationDetailsDTO : buListAccToCompany) {
				LOCATION_MAP_ADMIN.put(locationDetailsDTO.getLdId(), locationDetailsDTO);
				modelAndView.addObject("locationMap", LOCATION_MAP_ADMIN);			
			}
		}
//		modelAndView.addObject("companyList", companyList);
		modelAndView.addObject("bUList", bussinessUnitTypeList);
  		modelAndView.addObject("departmentMap", ApplicationMaps.DEPTID_DEPTSNAME_MAP);
		modelAndView.addObject("locationForm", locationForm);
		
		modelAndView.addObject("size", ApplicationMaps.LOCID_LOC_MAP.size());
		
		logger.debug("locationForm: " + locationForm);
		return modelAndView;
	}

	@RequestMapping("/viewDepartment")
	public ModelAndView viewDepartment() {
		ModelAndView mav = new ModelAndView("admin/viewDepartment");
		mav.addObject("departmentMap", ApplicationMaps.DEPARTMENTID_DEPARTMENT_MAP);
		mav.addObject("size", ApplicationMaps.DEPARTMENTID_DEPARTMENT_MAP.size());
		return mav;
	}

	@RequestMapping("/viewDocType")
	public ModelAndView viewDocType() {
		ModelAndView mav = new ModelAndView("admin/viewDocType");
		mav.addObject("docTypeMap", ApplicationMaps.DOCUMENT_TYPE_ID_MAP);
		mav.addObject("size", ApplicationMaps.DOCUMENT_TYPE_ID_MAP.size());
		return mav;
	}

	@RequestMapping("/viewDocCategory")
	public ModelAndView viewDocCategory() {
		ModelAndView mav = new ModelAndView("admin/viewDocCategory");
		
		mav.addObject("docTypeMap", ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP);
		mav.addObject("size", ApplicationMaps.DOC_TYP_DOC_CAT_MAP.size());
		mav.addObject("docTypeCatMap", ApplicationMaps.DOC_TYP_DOC_CAT_MAP);
		
		return mav;
	}

	@RequestMapping("/viewDocSubCategory")
	public ModelAndView viewDocSubCategory() {
		ModelAndView mav = new ModelAndView("admin/viewDocSubCategory");
		
		mav.addObject("docTypeMap", ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP);
		mav.addObject("size", ApplicationMaps.DOC_CAT_DOC_SUBCAT_MAP.size());
		mav.addObject("docTypeCatMap", ApplicationMaps.DOC_TYP_DOC_CAT_MAP);
		mav.addObject("docCatSubCatMap", ApplicationMaps.DOC_CAT_DOC_SUBCAT_MAP);
		return mav;
	}

	@RequestMapping("/viewUser")
	public ModelAndView viewUser() {
		logger.debug("inside method(viewUser)");
		ModelAndView mav = new ModelAndView("admin/viewUser");
        
        UserDetailsDTO userDetailsDTO = (UserDetailsDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<UserDetailsDTO> detailsDTOs = new ArrayList<UserDetailsDTO>();
        HashMap<Integer, CompanyDetailsDTO> COMPANY_MAP = new HashMap<Integer, CompanyDetailsDTO>();
                
        if(ApplicationConstants.ALL_INT.equals(userDetailsDTO.getCdId())){
//        	detailsDTOs  = authenticationService.loadAllUsersCompanyWise();
        	detailsDTOs = authenticationService.loadAllUsers();
        	COMPANY_MAP = ApplicationMaps.COMPANYID_COMPANY_MAP;
        }
        else{
        	List<UserDetailsDTO> loadedUsersList = authenticationService.loadAllUsersCompanyWise(); 
        	for (UserDetailsDTO userDetailsDTO2 : loadedUsersList) {
        		if(userDetailsDTO2.getCdId().equals(userDetailsDTO.getCdId())){
					detailsDTOs.add(userDetailsDTO2);
				}
			}
        	COMPANY_MAP.put(userDetailsDTO.getCdId(), ApplicationMaps.COMPANYID_COMPANY_MAP.get(userDetailsDTO.getCdId()));
        }
        
        mav.addObject("userList", detailsDTOs);
        mav.addObject("size", detailsDTOs.size());
        mav.addObject("locationMap", ApplicationMaps.LOCID_LOCNAME_MAP);
        mav.addObject("departmentMap", ApplicationMaps.DEPTID_DEPTSNAME_MAP);
        mav.addObject("companyMap", COMPANY_MAP);
        mav.addObject("companyId", userDetailsDTO.getCdId());
        return mav;

	}

	@RequestMapping("/fetchUsersAccToCompany")
	public ModelAndView fetchUsersAccToCompany(@RequestParam("formData") Integer cdId, @RequestParam("action") String formAction){
		logger.debug("COMPANY ID: " + cdId + " :formAction : " + (null!=formAction ? formAction : " -- "));
		
		UserDetailsDTO userDetailsDTO = (UserDetailsDTO)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		HashMap<Integer, CompanyDetailsDTO> COMPANY_MAP = new HashMap<Integer, CompanyDetailsDTO>();
		ModelAndView modelAndView = new ModelAndView("admin/viewUser");
		
		List<UserDetailsDTO> detailsDTOs;
		if(0 != cdId){
			logger.debug("Searching users for company with id: " + cdId);
			UserSearchForm userSearchForm = new UserSearchForm();
			userSearchForm.setCdId(cdId);
			if(null != formAction)
				userSearchForm.setFormAction(formAction);
			detailsDTOs = processDocumentService.searchedUserData(userSearchForm);
		}
		else{
			detailsDTOs = authenticationService.loadAllUsers();
		}
		
		if(ApplicationConstants.ALL_INT.equals(userDetailsDTO.getCdId())){
        	COMPANY_MAP = ApplicationMaps.COMPANYID_COMPANY_MAP;
        }
        else{
        	COMPANY_MAP.put(userDetailsDTO.getCdId(), ApplicationMaps.COMPANYID_COMPANY_MAP.get(userDetailsDTO.getCdId()));
        }
		
		modelAndView.addObject("userList", detailsDTOs);
		modelAndView.addObject("sizeOfUserList", detailsDTOs.size());
		modelAndView.addObject("locationMap", ApplicationMaps.LOCID_LOCNAME_MAP);
		modelAndView.addObject("departmentMap", ApplicationMaps.DEPTID_DEPTSNAME_MAP);
		modelAndView.addObject("companyMap", COMPANY_MAP);
		modelAndView.addObject("companyId", userDetailsDTO.getCdId());
		modelAndView.addObject("companySelect", cdId);
		return modelAndView;
	}
	
	@RequestMapping("/filterDeaprtment/{locId}")
	public void populateDepartment(@PathVariable("locId") String locId,
			HttpServletResponse response) {
		List<DepartmentDetailsDTO> dtos = ApplicationMaps.BU_DEPTS_MAP.get(Long
				.parseLong(locId));
		try {
			JSONArray array = new JSONArray();
			if (dtos != null) {
				for (DepartmentDetailsDTO detailsDTO : dtos) {
					HashMap<String, String> map = new HashMap<String, String>();
					Long deptId = detailsDTO.getDdId();
					map.put("optionValue", deptId.toString());
					map.put("optionDisplay", detailsDTO.getDdName());
					array.put(map);
				}
				response.getWriter().write(array.toString());
			}
		} catch (IOException e) {
			//e.printStackTrace();
			logger.error(e.getMessage());
		}
	}

	@RequestMapping("/workFlowRoleAssigner")
	public ModelAndView workFlowRoleAssign() throws JSONException, IOException {
		ModelAndView modelAndView = new ModelAndView();

		modelAndView.setViewName("admin/selectOptionsforWFRole");
		return modelAndView;
	}

	@RequestMapping("/generateWFRoleAssignTable")
	public void generateWFRoleAssignerTable(HttpServletResponse response)
			throws JSONException, IOException {
		JSONObject mainGridObject = new JSONObject();
		mainGridObject.put("page", 1);
		mainGridObject.put("total", 5);
		mainGridObject.put("records", 45);

		JSONArray gridRowArray = new JSONArray();
		JSONObject gridRow = new JSONObject();
		JSONObject columnObject = new JSONObject();
		JSONArray cellArray = new JSONArray();
		String masterCode = null;

		
		UserDetailsDTO loginUserDTO = (UserDetailsDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		logger.debug("company Id of login User: " + loginUserDTO.getCdId());
		
		for (Integer docTypeId : ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP.keySet()) {
			if(0 == loginUserDTO.getCdId()){
				for (Long locId : ApplicationMaps.LOCID_LOCNAME_MAP.keySet()) {
					for (DepartmentDetailsDTO depttId : ApplicationMaps.BU_DEPTS_MAP.get(locId)) {
						masterCode = docTypeId + "#" + locId + "#" + depttId.getDdId();
						cellArray = new JSONArray();
						cellArray.put(ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP.get(docTypeId));
						cellArray.put(ApplicationMaps.LOCID_LOCNAME_MAP.get(locId));
						cellArray.put(ApplicationMaps.DEPTID_DEPTSNAME_MAP.get(depttId.getDdId()));
						if (ApplicationMaps.ARMORY_REVIEVER_APPROVER.containsKey(masterCode)) {
							cellArray.put(ApplicationMaps.ARMORY_REVIEVER_APPROVER.get(masterCode).getReviewer());
							cellArray.put(ApplicationMaps.ARMORY_REVIEVER_APPROVER.get(masterCode).getApprover());
						} else {
							cellArray.put("");
							cellArray.put("");
						}
						cellArray.put(masterCode);
						columnObject = new JSONObject();
						columnObject.put("cell", cellArray);
						gridRowArray.put(columnObject);
					}
				}
			}
			else{
				HashMap<Long, String> LOC_MAP_ACC_TO_COMPANY = new HashMap<Long, String>();
				List<LocationDetailsDTO> locationListAccToCompany = ApplicationMaps.COMPANY_LOC_MAP.get(loginUserDTO.getCdId());
				for(LocationDetailsDTO location : locationListAccToCompany){
					LOC_MAP_ACC_TO_COMPANY.put(location.getLdId(), location.getLdName());
				}
				for (Long locId : LOC_MAP_ACC_TO_COMPANY.keySet()) {
					for (DepartmentDetailsDTO depttId : ApplicationMaps.BU_DEPTS_MAP.get(locId)) {
						masterCode = docTypeId + "#" + locId + "#" + depttId.getDdId();
						cellArray = new JSONArray();
						cellArray.put(ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP.get(docTypeId));
						cellArray.put(LOC_MAP_ACC_TO_COMPANY.get(locId));
						cellArray.put(ApplicationMaps.DEPTID_DEPTSNAME_MAP.get(depttId.getDdId()));
						if (ApplicationMaps.ARMORY_REVIEVER_APPROVER.containsKey(masterCode)) {
							cellArray.put(ApplicationMaps.ARMORY_REVIEVER_APPROVER.get(masterCode).getReviewer());
							cellArray.put(ApplicationMaps.ARMORY_REVIEVER_APPROVER.get(masterCode).getApprover());
						} else {
							cellArray.put("");
							cellArray.put("");
						}
						cellArray.put(masterCode);
						columnObject = new JSONObject();
						columnObject.put("cell", cellArray);
						gridRowArray.put(columnObject);
					}
				}
			}
			
		}

		mainGridObject.put("rows", gridRowArray);
		response.getWriter().write(mainGridObject.toString());
//		logger.debug(mainGridObject.toString(4));
	}

	@RequestMapping("/loadSelectDataForType")
	public ModelAndView loadSelectDataForType() {
		ModelAndView modelAndView = new ModelAndView();

		modelAndView.addObject("documentTypeMap",
				ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP);

		modelAndView.setViewName("admin/loadSelectDataForType");
		return modelAndView;
	}

	@RequestMapping("/loadSelectDataForLocation")
	public ModelAndView loadSelectDataForLocation() {
		ModelAndView modelAndView = new ModelAndView();

		modelAndView
				.addObject("locationMap", ApplicationMaps.LOCID_LOCNAME_MAP);

		modelAndView.setViewName("admin/loadSelectDataForLocation");
		return modelAndView;
	}

	@RequestMapping("/loadSelectDataForDepartment")
	public ModelAndView loadSelectDataForDepartment() {
		ModelAndView modelAndView = new ModelAndView();

		modelAndView.addObject("departmentMap",
				ApplicationMaps.DEPTID_DEPTSNAME_MAP);

		modelAndView.setViewName("admin/loadSelectDataForDepartment");
		return modelAndView;
	}

	@RequestMapping("/editDataInWFTable")
	public void editDataInWFTable(
			@ModelAttribute SaveDataInWFTable saveDataInWFTable,
			HttpServletResponse response) throws IOException {
		logger.debug("REQUEST");
		logger.debug(saveDataInWFTable.getDocumentType());
		logger.debug(saveDataInWFTable.getDocumentLocation());
		logger.debug(saveDataInWFTable.getDocumentDepartment());
		logger.debug(saveDataInWFTable.getApprover());
		logger.debug(saveDataInWFTable.getReviewer());
		logger.debug(saveDataInWFTable.getMasterCode());
		response.getWriter().write("");
		flowService.submitWFRoleDetails(saveDataInWFTable);

	}
	@RequestMapping("/submitMasterDataInMasterWFTable")
	public ModelAndView submitMasterDataInMasterWFTable(@RequestParam("dataForWF") String[] dataForWF){
		
		logger.debug("dataForWF" + dataForWF);
		
		ModelAndView modelAndView = new ModelAndView();
		
		Set<String> dataForWFTable = new HashSet<String>();
		if(dataForWF != null && dataForWF.length > 0){
			dataForWFTable.addAll(Arrays.asList(dataForWF));
		}
		logger.debug(dataForWFTable);
		
		if(adminService.insertDataInMasterDetailsTable(dataForWFTable)){
			modelAndView.setViewName("loginPage");
			logger.debug("Success");
			
		}
		else{
			modelAndView.setViewName("admin/welcomeAdmin");
			logger.debug("FAILURE");
		}
		logger.debug(modelAndView.getViewName());
		return modelAndView;
		
	
	}
	
	@RequestMapping("/loadRelatedBelowValuesForDistrict")
	public void loadRelatedBelowValues(@RequestParam("selectedId") String selectedValue, HttpServletResponse response){
		JSONArray districtsArray = new JSONArray();
		districtsArray =  adminService.loadAllDistrictsAccToState(selectedValue);
				
		try{
			response.getWriter().write(districtsArray.toString());
		}
		catch (IOException e) {
			//e.printStackTrace();
			logger.error(e.getMessage());
		}
	}
	
	@RequestMapping("/loadRelatedBelowValuesForCity")
	public void loadRelatedBelowValuesForSelectedValues(@RequestParam("selectedId") String selectedValue, HttpServletResponse response){
		
		JSONArray cityArray = new JSONArray();
		
		cityArray =  adminService.loadAllCityAccToDistrict(selectedValue);
				
		try{
			response.getWriter().write(cityArray.toString());
		}
		catch (IOException e) {
			//e.printStackTrace();
			logger.error(e.getMessage());
		}
	}

	@RequestMapping("/delCompany")
	public ModelAndView delCompany(){
		ModelAndView modelAndView = new ModelAndView("admin/delCompany");
		
		LocationMasterDTO locationMasterDTOs = new LocationMasterDTO();
		List<LocationMasterDTO> locationMasterDTO = adminService.loadLocationDetails(locationMasterDTOs);
		
		modelAndView.addObject("companyMap", ApplicationMaps.COMPANYID_COMPANY_MAP);
		modelAndView.addObject("locationMasterDTO", locationMasterDTO);
				
		return modelAndView;
	}
	
	@RequestMapping("/deleteCompany")
	public ModelAndView deleteCompany(@RequestParam("cdId") Integer cdId){
		ModelAndView modelAndView = new ModelAndView("admin/delCompany");
				
		logger.debug("company Id to delete: "+cdId);
		LocationMasterDTO locationMasterDTOs = new LocationMasterDTO();
		List<LocationMasterDTO> locationMasterDTO = adminService.loadLocationDetails(locationMasterDTOs);
		CompanyDetailsDTO companyDetailsDTO = ApplicationMaps.COMPANYID_COMPANY_MAP.get(cdId);
		
		boolean resultOfDel = adminService.deleteCompany(companyDetailsDTO);
		
		modelAndView.addObject("resultOfDel", resultOfDel);
		modelAndView.addObject("locationMasterDTO", locationMasterDTO);
		modelAndView.addObject("companyMap", ApplicationMaps.COMPANYID_COMPANY_MAP);
		
		logger.debug("resultOfDel: " + resultOfDel);
		return modelAndView;
	}
	
	@RequestMapping("/editBusinessUnitType")
	public ModelAndView editBusinessUnitType(){
		ModelAndView modelAndView = new ModelAndView("admin/editBusinessUnitType");
		
		BusinessUnitTypeDTO businessUnitTypeDTO = new BusinessUnitTypeDTO();
		
		//List<BusinessUnitTypeDTO> businessUnitList = adminService.loadAllBU();
		modelAndView.addObject("businessUnitList", ApplicationMaps.BUTYPE_NAME_DESC_MAP);
		modelAndView.addObject("size", ApplicationMaps.BUTYPE_NAME_DESC_MAP.size());
		modelAndView.addObject("businessUnitTypeDTO", businessUnitTypeDTO);
		
		return modelAndView;
	}
	
	@RequestMapping("saveBusinessUnitTypeDetails")
	public ModelAndView saveBusinessUnitTypeDetails(@Valid BusinessUnitTypeDTO businessUnitTypeDTO, BindingResult bindingResult) {
		
		ModelAndView modelAndView = new ModelAndView("admin/addBussinessUnitType");
		boolean resultOfSave = false;
		
		if(bindingResult.getErrorCount() > 0) {
			modelAndView.addObject("errorCount", bindingResult.getErrorCount());
		}
		else {
			if(ApplicationMaps.BUTYPE_NAME_DESC_MAP.containsKey(businessUnitTypeDTO.getBuTypeCode())){
				FieldError fieldError = new FieldError("businessUnitTypeDTO","buTypeCode" , "Buisness Unit type with this code already exists");
				bindingResult.addError(fieldError);
			}
			else if(ApplicationMaps.BUTYPE_NAME_DESC_MAP.containsValue(businessUnitTypeDTO.getBuTypeName())) {
				FieldError fieldError = new FieldError("businessUnitTypeDTO","buTypeName" , "Buisness Unit type with this name already exists");
				bindingResult.addError(fieldError);
			}
			else {
				resultOfSave = adminService.saveUnitTypeEditDetails(businessUnitTypeDTO);
			}
			modelAndView.addObject("resultOfSave", resultOfSave);
			logger.debug("Result Of Save of unit type edit details: " + resultOfSave);
			modelAndView.addObject("errorCount", 0);
		}
		
		modelAndView.addObject("businessUnitList", ApplicationMaps.BUTYPE_NAME_DESC_MAP);
		modelAndView.addObject("size", ApplicationMaps.BUTYPE_NAME_DESC_MAP.size());
		modelAndView.addObject("businessUnitTypeDTO", businessUnitTypeDTO);
			
		return modelAndView;
	}
	
	@RequestMapping("editBusinessUnitTypeDetails")
	public ModelAndView editBusinessUnitTypeDetails(@Valid BusinessUnitTypeDTO businessUnitTypeDTO, BindingResult bindingResult){
		ModelAndView modelAndView = new ModelAndView("admin/editBusinessUnitType");
		
		if(bindingResult.getErrorCount() > 0){}
		else{
			boolean resultOfSave = adminService.editUnitTypeDetails(businessUnitTypeDTO);
			modelAndView.addObject("resultOfSave", resultOfSave);
		}
		
		modelAndView.addObject("businessUnitList", ApplicationMaps.BUTYPE_NAME_DESC_MAP);
		modelAndView.addObject("size", ApplicationMaps.BUTYPE_NAME_DESC_MAP.size());
		modelAndView.addObject("businessUnitTypeDTO", businessUnitTypeDTO);
			
		return modelAndView;
	}
	
	@RequestMapping("/editDepartmentDetails")
	public ModelAndView editDepartmentDetails(){
		ModelAndView modelAndView = new ModelAndView("admin/editDepartment");
		
		DepartmentDetailsDTO departmentDetailsDTO = new DepartmentDetailsDTO();
		
		modelAndView.addObject("departmentsList", ApplicationMaps.DEPARTMENTID_DEPARTMENT_MAP);
		modelAndView.addObject("size", ApplicationMaps.DEPARTMENTID_DEPARTMENT_MAP.size());
		modelAndView.addObject("departmentDetailsDTO", departmentDetailsDTO);
		return modelAndView;
		
	}

	@RequestMapping("saveDepartmentEditDetails")
	public ModelAndView saveDepartmentEditDetails(@Valid DepartmentDetailsDTO departmentDetailsDTO, BindingResult bindingResult){
		ModelAndView modelAndView = new ModelAndView("admin/editDepartment");
		
		FieldError fieldError = null;
		
		/*if(departmentDetailsDTO.getDdId() == 0){
			fieldError = new FieldError("detailsDTO", "ddId", "Please enter a valid department Id.");
			bindingResult.addError(fieldError);
		}*/
		if(departmentDetailsDTO.getDdName().isEmpty()){
			fieldError = new FieldError("detailsDTO", "ddName", "Please enter a valid department name.");
			bindingResult.addError(fieldError);
		}
		if(ApplicationMaps.DEPTID_DEPTSNAME_MAP.values().contains(departmentDetailsDTO.getDdName())){
			fieldError = new FieldError("detailsDTO", "ddName", "Department with this name already exists. Please enter different name");
			bindingResult.addError(fieldError);
		}
		if(departmentDetailsDTO.getDdCode().isEmpty()){
			fieldError = new FieldError("detailsDTO", "ddCode", "Please enter a valid department code.");
			bindingResult.addError(fieldError);
		}
		
		if(bindingResult.getErrorCount() > 0){}
		else{
			boolean resultOfSave = adminService.saveDepartmentEditDetails(departmentDetailsDTO);
			modelAndView.addObject("resultOfSave", resultOfSave);
		}
		
		modelAndView.addObject("departmentsList", ApplicationMaps.DEPARTMENTID_DEPARTMENT_MAP);
		modelAndView.addObject("size", ApplicationMaps.DEPARTMENTID_DEPARTMENT_MAP.size());
		modelAndView.addObject("departmentDetailsDTO", departmentDetailsDTO);
		
		return modelAndView;
	}
	
	

	@RequestMapping("/fetchDetailsOfSelectedBU")
	public ModelAndView fetchDetailsOfSelectedBU(@RequestParam("ldId") Long ldId){
		ModelAndView modelAndView = new ModelAndView("admin/editBusinessUnit");
		
		logger.debug("location Id: "+ldId);
		
		LocationDetailsDTO locationDetailsDTO = ApplicationMaps.LOCID_LOC_MAP.get(ldId);
		
		logger.debug("locationDetailsDTO" + locationDetailsDTO);
		logger.debug(locationDetailsDTO.getDepartmentDetailsDTOs().size());
		
		List<DepartmentDetailsDTO> depttList = locationDetailsDTO.getDepartmentDetailsDTOs();
		Long deptt[] = new Long[locationDetailsDTO.getDepartmentDetailsDTOs().size()];
		ArrayList<CompanyDetailsDTO> companyList = new ArrayList<CompanyDetailsDTO>();
		companyList.addAll(ApplicationMaps.COMPANYID_COMPANY_MAP.values());
		ArrayList<BusinessUnitTypeDTO> bussinessUnitTypeList = (ArrayList<BusinessUnitTypeDTO>) adminService.loadAllBU();
		
		int i = 0;
		for(DepartmentDetailsDTO depttdetails : depttList){
			
				logger.debug(depttdetails.getDdId());
				deptt[i] = depttdetails.getDdId();
				i++;
			
		}
		
		logger.debug("department array: "+deptt.length);
		
		LocationForm locationForm = new LocationForm();
		
		locationForm.setLdName(locationDetailsDTO.getLdName());
		locationForm.setLdCode(locationDetailsDTO.getLdCode());
		locationForm.setLdCompanyId(locationDetailsDTO.getLdCompanyId());
		locationForm.setLdType(locationDetailsDTO.getLdType());
		locationForm.setDdId(deptt);
		locationForm.setLdId(locationDetailsDTO.getLdId());
		
		modelAndView.addObject("locationForm", locationForm);
		modelAndView.addObject("companyList", companyList);
		modelAndView.addObject("bUList", bussinessUnitTypeList);
  		modelAndView.addObject("departmentMap", ApplicationMaps.DEPTID_DEPTSNAME_MAP);
		modelAndView.addObject("locationMap", ApplicationMaps.LOCID_LOC_MAP);
		modelAndView.addObject("size", ApplicationMaps.LOCID_LOC_MAP.size());
		
		logger.debug("locationForm: " + locationForm);
		
		return modelAndView;
	}
	
	@RequestMapping("/saveBusinessUnitNewDetails")
	public ModelAndView saveLocationNewDetails(@Valid LocationForm locationForm, BindingResult bindingResult){
		ModelAndView modelAndView = new ModelAndView("admin/editBusinessUnit");
		
		ArrayList<CompanyDetailsDTO> companyList = new ArrayList<CompanyDetailsDTO>();
		companyList.addAll(ApplicationMaps.COMPANYID_COMPANY_MAP.values());
		ArrayList<BusinessUnitTypeDTO> bussinessUnitTypeList = (ArrayList<BusinessUnitTypeDTO>) adminService.loadAllBU();
		
		FieldError fieldError =null;
		
		/*if(locationForm.getLdName().isEmpty()){
			fieldError = new FieldError("locationDetailsDTO", "ldName", "The field cannot be blank");
			bindingResult.addError(fieldError);
		}
		if(locationForm.getLdCode().isEmpty()){
			fieldError = new FieldError("locationDetailsDTO", "ldCode", "The field cannot be blank.");
			bindingResult.addError(fieldError);
		}*/
		if(locationForm.getLdCompanyId().getCdId() == 0){
			fieldError = new FieldError("locationDetailsDTO", "ldCompanyId.cdId", "Please select a valid company from the list.");
			bindingResult.addError(fieldError);
		}
		if(locationForm.getLdType().isEmpty()){
			fieldError = new FieldError("locationDetailsDTO", "ldType", "Please select a valid type from the list.");
			bindingResult.addError(fieldError);
		}
		if(locationForm.getDdId().length == 0){
			fieldError = new FieldError("locationDetailsDTO", "departmentDetailsDTOs", "Please select a valid department from the list");
			bindingResult.addError(fieldError);
		}
		/*if(locationDetailsDTO.getLdCode().isEmpty()){
			fieldError = new FieldError("locationDetailsDTO", "", "");
			bindingResult.addError(fieldError);
		}*/
	
		if(bindingResult.getErrorCount()>0){}
		else{
			boolean resultOfSave = adminService.saveBusinessUnitEditDetails(locationForm);
			modelAndView.addObject("resultOfSave",resultOfSave);
		}
		
		modelAndView.addObject("companyList", companyList);
  		modelAndView.addObject("departmentMap", ApplicationMaps.DEPTID_DEPTSNAME_MAP);
		modelAndView.addObject("locationDetailsDTO", locationForm);
		modelAndView.addObject("locationMap", ApplicationMaps.LOCID_LOC_MAP);
		modelAndView.addObject("size", ApplicationMaps.LOCID_LOC_MAP.size());
		modelAndView.addObject("bUList", bussinessUnitTypeList);
		
		return modelAndView;
		
	}
	
	@RequestMapping("/searchUserToEdit")
	public ModelAndView searchUserToEdit(){
		ModelAndView modelAndView = new ModelAndView("admin/searchUserForEditing");
		
		return modelAndView;
	}
	
	@RequestMapping("/editUserDetails")
	public ModelAndView editUserDetails(@RequestParam("userIdResult") String userId){
		ModelAndView modelAndView = new ModelAndView("admin/editUserDetails");
		UserDetailsDTO userDetailsDTO = null;
		String enablePasswordEdit = null;
		Properties properties = new Properties();
		
		if(ApplicationMaps.USERID_USERNAME_MAP.containsKey(userId))
			userDetailsDTO = authenticationService.getUserForProvidedUserId(userId);
		else{
			modelAndView.addObject("result", true);
			modelAndView.setViewName("admin/searchUserForEditing");
			return modelAndView;
		}
		
		try {
			List<GrantedAuthority> authorities = (List<GrantedAuthority>) userDetailsDTO.getAuthorities();
			List<String> list = new ArrayList<String>();
			for(GrantedAuthority authority:authorities)
			{
				RoleDetailsDTO detailsDTO = (RoleDetailsDTO) authority;
				logger.debug(detailsDTO.getRoleId());
				list.add(detailsDTO.getRoleId());
			}					
			String [] role = new String[list.toArray().length];
			for (int i=0;i<list.toArray().length;i++) 
				{
					role[i]=list.toArray()[i].toString();						
				}
			userDetailsDTO.setRole(role);
			
			properties.load(AuthenticationService.class.getResourceAsStream("/armory.properties"));
			enablePasswordEdit = properties.getProperty("enablePasswordEdit");
			
			if(null != enablePasswordEdit){
				modelAndView.addObject("enablePasswordEdit", enablePasswordEdit);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		ArrayList<LocationDetailsDTO> locationList = new ArrayList<LocationDetailsDTO>();
		locationList.addAll(ApplicationMaps.LOCID_LOC_MAP.values());
		
		HashMap<Integer, CompanyDetailsDTO> COMPANY_MAP = new HashMap<Integer, CompanyDetailsDTO>();
		UserDetailsDTO detailsDTO = (UserDetailsDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		
		
		if(detailsDTO.getCdId() == 0){
			COMPANY_MAP = ApplicationMaps.COMPANYID_COMPANY_MAP;
		}
		else{
			COMPANY_MAP.put(detailsDTO.getCdId(), ApplicationMaps.COMPANYID_COMPANY_MAP.get(detailsDTO.getCdId()));
		}
		
		modelAndView.addObject("userDetailsDTO", userDetailsDTO);
		modelAndView.addObject("locationList", locationList);
		modelAndView.addObject("locationMap", ApplicationMaps.LOCID_LOC_MAP);
		modelAndView.addObject("departmentMap", ApplicationMaps.DEPTID_DEPTSNAME_MAP);
		modelAndView.addObject("companyMap", COMPANY_MAP);
		
		return modelAndView; 
	}
	
	@RequestMapping("/submitUserDetailsAfterEditing")
	public ModelAndView submitUserDetailsAfterEditing(@Valid UserDetailsDTO userDetailsDTO, BindingResult bindingResult){
		ModelAndView modelAndView = new ModelAndView("admin/editUserDetails");
		Properties properties = new Properties();
		String enablePasswordEdit = null;
		String defaultPassword = null;
		try{
			properties.load(AuthenticationService.class.getResourceAsStream("/armory.properties"));
			enablePasswordEdit = properties.getProperty("enablePasswordEdit");
			defaultPassword = properties.getProperty("defaultPassword");
		}
		catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		
		if(null != enablePasswordEdit){
			if(enablePasswordEdit.equalsIgnoreCase(ApplicationConstants.DISABLE_FUNCTION)){
				System.out.println("enablePasswordEdit: " + enablePasswordEdit);
				System.out.println("defaultpassword: " + defaultPassword);
				if(null != defaultPassword)
					userDetailsDTO.setPassword(defaultPassword);
			}
			modelAndView.addObject("enablePasswordEdit", enablePasswordEdit);
		}
		
		ArrayList<LocationDetailsDTO> locationList = new ArrayList<LocationDetailsDTO>();
		locationList.addAll(ApplicationMaps.LOCID_LOC_MAP.values());
	
		FieldError fieldError = null;
		
		if(userDetailsDTO.getUsername().isEmpty()){
			fieldError = new FieldError("userDetailsDTO", "username", "The field cannot be blank.");
			bindingResult.addError(fieldError);
		}
		if(userDetailsDTO.getUserDisplayName().isEmpty()){
			fieldError = new FieldError("userDetailsDTO", "userDisplayName", "The field cannot be blank.");
			bindingResult.addError(fieldError);
		}
		if(userDetailsDTO.getPassword().isEmpty()){
			fieldError = new FieldError("userDetailsDTO", "password", "The field cannot be blank.");
			bindingResult.addError(fieldError);
		}
		if(userDetailsDTO.getCdId() == 0){
			fieldError = new FieldError("userDetailsDTO", "cdId", "Please select a valid company from the list.");
			bindingResult.addError(fieldError);
		}
		if(userDetailsDTO.getBuId() == 0){
			fieldError = new FieldError("userDetailsDTO", "buId", "Please select a valid business unit from the list.");
			bindingResult.addError(fieldError);
		}
		if(userDetailsDTO.getDeptId() == 0){
			fieldError = new FieldError("userDetailsDTO", "deptId", "Please select a valid department from the list.");
			bindingResult.addError(fieldError);
		}
		if(userDetailsDTO.getEmailId().matches(ApplicationConstants.REGEX_FOR_EMAIL)){
			fieldError = new FieldError("userDetailsDTO", "emailId", "Please enter email id in proper format.");
			bindingResult.addError(fieldError);
		}
		
		if(bindingResult.getErrorCount() > 0){
			logger.debug(bindingResult.getFieldErrors());
			
			userDetailsDTO = authenticationService.getUserForProvidedUserId(userDetailsDTO.getUsername());
			List<GrantedAuthority> authorities = (List<GrantedAuthority>) userDetailsDTO.getAuthorities();
			List<String> list = new ArrayList<String>();
			for(GrantedAuthority authority:authorities)
			{
				RoleDetailsDTO detailsDTO1 = (RoleDetailsDTO) authority;
				logger.debug(detailsDTO1.getRoleDesc());
				list.add(detailsDTO1.getRoleDesc());
			}					
			String [] role = new String[list.toArray().length];
			for (int i=0;i<list.toArray().length;i++) 
				{
					role[i]=list.toArray()[i].toString();						
				}
			userDetailsDTO.setRole(role);
		}
		else{
			/*password encryption in edit user (admin module)*/
			String enteredPassword = userDetailsDTO.getPassword();
			PasswordEncoder encoder = new ShaPasswordEncoder(256);
			String encPassword = encoder.encodePassword(enteredPassword, null);
			userDetailsDTO.setPassword(encPassword);
			
			boolean resultOfSave = authenticationService.saveUserDetailsAfterEditing(userDetailsDTO);
			modelAndView.addObject("resultOfSave", resultOfSave);
		}
		
		modelAndView.addObject("userDetailsDTO", userDetailsDTO);
		modelAndView.addObject("locationList", locationList);
		modelAndView.addObject("departmentMap", ApplicationMaps.DEPTID_DEPTSNAME_MAP);
		modelAndView.addObject("companyMap1", ApplicationMaps.COMPANYID_COMPANY_MAP.values());
		modelAndView.addObject("companyMap", ApplicationMaps.COMPANYID_COMPANY_MAP);
		
		return modelAndView;
	}
	
	@RequestMapping("/editDocumentTypeDetails")
	public ModelAndView editDocumentTypeDetails(){
		ModelAndView modelAndView = new ModelAndView("admin/editDocumentType");
		
		DocumentTypeDTO documentTypeDTO = new DocumentTypeDTO();
		
		modelAndView.addObject("documentTypeDTO", documentTypeDTO);
		modelAndView.addObject("docTypeMap", ApplicationMaps.DOCUMENT_TYPE_ID_MAP);
		modelAndView.addObject("size", ApplicationMaps.DOCUMENT_TYPE_ID_MAP.size());
		
		return modelAndView;
	}
	
	@RequestMapping("/saveDocTypeNewDetails")
	public ModelAndView saveDocTypeNewDetails(@Valid DocumentTypeDTO documentTypeDTO, BindingResult bindingResult){
		ModelAndView modelAndView = new ModelAndView("admin/editDocumentType");
		
		if(bindingResult.getErrorCount() > 0){}
		else{
			boolean resultOfSave = adminService.updateTypeDetails(documentTypeDTO);
			modelAndView.addObject("resultOfSave", resultOfSave);
		}
		
		modelAndView.addObject("documentTypeDTO", documentTypeDTO);
		modelAndView.addObject("docTypeMap", ApplicationMaps.DOCUMENT_TYPE_ID_MAP);
		modelAndView.addObject("size", ApplicationMaps.DOCUMENT_TYPE_ID_MAP.size());
		
		return modelAndView;
		
	}
	
	@RequestMapping("/editDocCategoryDetails")
	public ModelAndView editDocCategoryDetails(){
		ModelAndView modelAndView = new ModelAndView("admin/editDocCategory");
		
		DocumentCategoryDTO documentCategoryDTO = new DocumentCategoryDTO();
		ArrayList<DocumentTypeDTO> docTypeList = new ArrayList<DocumentTypeDTO>();
		docTypeList.addAll(ApplicationMaps.DOCUMENT_TYPE_ID_MAP.values());
		
		
		modelAndView.addObject("documentCategoryDTO", documentCategoryDTO);
		modelAndView.addObject("docTypeList", docTypeList);
		modelAndView.addObject("docTypeMap1", ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP);
		modelAndView.addObject("docTypeMap", ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP);
		modelAndView.addObject("size", ApplicationMaps.DOC_TYP_DOC_CAT_MAP.size());
		modelAndView.addObject("docTypeCatMap", ApplicationMaps.DOC_TYP_DOC_CAT_MAP);
		
		return modelAndView;
	}
	
	@RequestMapping("/saveDocCategoryNewDetails")
	public ModelAndView saveDocCategoryNewDetails(@Valid DocumentCategoryDTO documentCategoryDTO, BindingResult bindingResult){
		ModelAndView modelAndView = new ModelAndView("admin/editDocCategory");
		
		ArrayList<DocumentTypeDTO> docTypeList = new ArrayList<DocumentTypeDTO>();
		docTypeList.addAll(ApplicationMaps.DOCUMENT_TYPE_ID_MAP.values());
		
		FieldError fieldError;
		
		/*if(documentCategoryDTO.getDcName().isEmpty()){
			
			fieldError = new FieldError("documentCategoryDTO", "dcName", "The field cannot be blank.");
			bindingResult.addError(fieldError);
		}*/
		if(documentCategoryDTO.getDcParentType().getDtId() == 0){
			
			fieldError = new FieldError("documentCategoryDTO", "dcParentType.dtId", "Please select a valid type from the list.");
			bindingResult.addError(fieldError);
		}
		
		if(bindingResult.getErrorCount() > 0){
			
			logger.debug(bindingResult.getFieldErrors());
		}
		else{
			
			boolean resultOfSave = adminService.updateDocCategoryDetails(documentCategoryDTO);
			modelAndView.addObject("resultOfSave", resultOfSave);
		}
		
		DocumentCategoryDTO documentCategoryDTO2 = new DocumentCategoryDTO();
		
		modelAndView.addObject("documentCategoryDTO", documentCategoryDTO2);
		modelAndView.addObject("docTypeList", docTypeList);
		modelAndView.addObject("docTypeMap", ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP);
		modelAndView.addObject("size", ApplicationMaps.DOC_TYP_DOC_CAT_MAP.size());
		modelAndView.addObject("docTypeCatMap", ApplicationMaps.DOC_TYP_DOC_CAT_MAP);
		
		return modelAndView;
	}
	
	@RequestMapping("/editDocSubCategoryDetails")
	public ModelAndView editDocSubCategoryDetails(){
		ModelAndView modelAndView = new ModelAndView("admin/editDocSubCategory");
		
		DocumentSubCategory documentSubCategory = new DocumentSubCategory();
		
		modelAndView.addObject("documentSubCategory", documentSubCategory);
		modelAndView.addObject("docTypeMap", ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP);
		modelAndView.addObject("docTypeMap1", ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP);
		modelAndView.addObject("size", ApplicationMaps.DOC_CAT_DOC_SUBCAT_MAP.size());
		modelAndView.addObject("docTypeCatMap", ApplicationMaps.DOC_TYP_DOC_CAT_MAP);
		modelAndView.addObject("docCatSubCatMap", ApplicationMaps.DOC_CAT_DOC_SUBCAT_MAP);
		
		return modelAndView;
	}
	
	@RequestMapping("/saveDocSubCategoryNewDetails")
	public ModelAndView saveDocSubCategoryNewDetails(@Valid DocumentSubCategory documentSubCategory, BindingResult bindingResult){
		ModelAndView modelAndView = new ModelAndView("admin/editDocSubCategory");
		
		FieldError fieldError = null;
		
		if(documentSubCategory.getDscParentCategory().getDcParentType().getDtId() == 0){
			fieldError = new FieldError("documentSubCategory", "dscParentCategory.dcId", "Choose a valid type from the list.");
			bindingResult.addError(fieldError);
		}
		
		if(bindingResult.getErrorCount() > 0){}
		else{
			boolean resultOfSave = adminService.saveDocSubCategoryNewDetails(documentSubCategory);
			modelAndView.addObject("resultOfSave", resultOfSave);
		}
		
		DocumentSubCategory documentSubCategory2 = new DocumentSubCategory();
		
		modelAndView.addObject("documentSubCategory", documentSubCategory2);
		modelAndView.addObject("docTypeMap1", ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP);
		modelAndView.addObject("docTypeMap", ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP);
		modelAndView.addObject("size", ApplicationMaps.DOC_CAT_DOC_SUBCAT_MAP.size());
		modelAndView.addObject("docTypeCatMap", ApplicationMaps.DOC_TYP_DOC_CAT_MAP);
		modelAndView.addObject("docCatSubCatMap", ApplicationMaps.DOC_CAT_DOC_SUBCAT_MAP);
		
		return modelAndView;
	}
	
	@RequestMapping("/fetchCategAccToType")
	public ModelAndView fetchCategAccToSubCateg(@RequestParam("formData") Integer dtId){
		logger.debug("Document Type Id: " + dtId);
		
		ModelAndView modelAndView = new ModelAndView("admin/editDocCategory");
		
		DocumentCategoryDTO documentCategoryDTO = new DocumentCategoryDTO();
		
		ArrayList<DocumentTypeDTO> docTypeList = new ArrayList<DocumentTypeDTO>();
		docTypeList.addAll(ApplicationMaps.DOCUMENT_TYPE_ID_MAP.values());
		
		if(null != dtId){
			if(dtId != 0){
				List<DocumentCategoryDTO> categoryDTOs = ApplicationMaps.DOC_TYP_DOC_CAT_MAP.get(dtId);
				HashMap<Integer, List<DocumentCategoryDTO>> DOC_CAT_TYPE_MAP = new HashMap<Integer, List<DocumentCategoryDTO>>();
				DOC_CAT_TYPE_MAP.put(dtId,categoryDTOs);
				
				HashMap<Integer, String> docTypeMap = new HashMap<Integer, String>();
				docTypeMap.put(dtId, ApplicationMaps.DOCUMENT_TYPE_ID_MAP.get(dtId).getDtName());
				modelAndView.addObject("docTypeMap", docTypeMap);
				modelAndView.addObject("docTypeCatMap", DOC_CAT_TYPE_MAP);
				
				
				logger.debug("DOCUMENT_TYPE_ID_NAME_MAP" + docTypeMap);
			}
			else{
				modelAndView.addObject("docTypeMap", ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP);
				modelAndView.addObject("docTypeCatMap", ApplicationMaps.DOC_TYP_DOC_CAT_MAP);
				
				logger.debug("DOCUMENT_TYPE_ID_NAME_MAP" + ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP);
			}
		}
		
		modelAndView.addObject("docTypeMap1", ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP);
		modelAndView.addObject("size", ApplicationMaps.DOC_TYP_DOC_CAT_MAP.size());
		
		modelAndView.addObject("documentCategoryDTO", documentCategoryDTO);
		modelAndView.addObject("docTypeList", docTypeList);
		modelAndView.addObject("docTypeID", dtId);

		return modelAndView;
	}
	
	@RequestMapping("/fetchSubCategAccToCateg")
	public ModelAndView fetchSubCategAccToCateg(@RequestParam("docCateg") Integer dcId, @RequestParam("docType") Integer dtId){
		ModelAndView modelAndView = new ModelAndView("admin/editDocSubCategory");
		
		DocumentSubCategory documentSubCategory = new DocumentSubCategory();
		
		
		if(dtId != null){
			if(dtId != 0){
				if(dcId != 0){
					HashMap<Integer, List<DocumentSubCategory>> DOC_SUBCAT_MAP = new HashMap<Integer, List<DocumentSubCategory>>();
					HashMap<Integer, List<DocumentCategoryDTO>> DOC_CAT_MAP = new HashMap<Integer, List<DocumentCategoryDTO>>();
					HashMap<Integer, String> DOC_TYPE_MAP = new HashMap<Integer, String>();
					
					DOC_TYPE_MAP.put(dtId, ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP.get(dtId));
					DOC_CAT_MAP.put(dtId, ApplicationMaps.DOC_TYP_DOC_CAT_MAP.get(dtId));
					DOC_SUBCAT_MAP.put(dcId, ApplicationMaps.DOC_CAT_DOC_SUBCAT_MAP.get(dcId));
					
					modelAndView.addObject("docTypeCatMap", DOC_CAT_MAP);
					modelAndView.addObject("docCatSubCatMap", DOC_SUBCAT_MAP);
					modelAndView.addObject("docTypeMap", DOC_TYPE_MAP);
					
					logger.debug("DOC_SUBCAT_MAP: " + DOC_SUBCAT_MAP);
					logger.debug("DOC_CAT_MAP: " + DOC_CAT_MAP);
				}
				else{
					HashMap<Integer, List<DocumentSubCategory>> DOC_SUBCAT_MAP = new HashMap<Integer, List<DocumentSubCategory>>();
					HashMap<Integer, List<DocumentCategoryDTO>> DOC_CAT_MAP = new HashMap<Integer, List<DocumentCategoryDTO>>();
					HashMap<Integer, String> DOC_TYPE_MAP = new HashMap<Integer, String>();
					
					DOC_TYPE_MAP.put(dtId, ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP.get(dtId));
					DOC_CAT_MAP.put(dtId, ApplicationMaps.DOC_TYP_DOC_CAT_MAP.get(dtId));
					List<DocumentCategoryDTO> docCatList = ApplicationMaps.DOC_TYP_DOC_CAT_MAP.get(dtId);
					if(null != docCatList){
						for (DocumentCategoryDTO documentCategory : docCatList) {
							DOC_SUBCAT_MAP.put(documentCategory.getDcId(), ApplicationMaps.DOC_CAT_DOC_SUBCAT_MAP.get(documentCategory.getDcId()));
						}
					}
					
					modelAndView.addObject("docTypeCatMap", DOC_CAT_MAP);
					modelAndView.addObject("docCatSubCatMap", DOC_SUBCAT_MAP);
					modelAndView.addObject("docTypeMap", DOC_TYPE_MAP);
					
					logger.debug("DOC_SUBCAT_MAP: " + DOC_SUBCAT_MAP);
					logger.debug("DOC_CAT_MAP: " + DOC_CAT_MAP);
				}
			}
			else{
				modelAndView.addObject("docTypeMap", ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP);
				modelAndView.addObject("docTypeCatMap", ApplicationMaps.DOC_TYP_DOC_CAT_MAP);
				modelAndView.addObject("docCatSubCatMap", ApplicationMaps.DOC_CAT_DOC_SUBCAT_MAP);
				
				logger.debug("DOC_SUBCAT_MAP: " + ApplicationMaps.DOC_CAT_DOC_SUBCAT_MAP);
				logger.debug("DOC_CAT_MAP: " + ApplicationMaps.DOC_TYP_DOC_CAT_MAP);
			}
		}
	
		
		modelAndView.addObject("documentSubCategory", documentSubCategory);
		modelAndView.addObject("docTypeMap1", ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP);
		modelAndView.addObject("size", ApplicationMaps.DOC_CAT_DOC_SUBCAT_MAP.size());
		
		modelAndView.addObject("docType", dtId);
		modelAndView.addObject("docCat", dcId);
		
		return modelAndView;
	}
	
	@RequestMapping("/filterSubcategoryListbyType")
	public void filterSubcategoryListbyType(@RequestParam("id") Integer dtId){/*
		logger.debug("Document Id: " + dtId);
		ModelAndView modelAndView = new ModelAndView("admin/editDocSubCategory");
		
		if(null != dtId){
			if(0 != dtId){
				HashMap<Integer, List<DocumentSubCategory>> DOC_SUBCAT_MAP = new HashMap<Integer, List<DocumentSubCategory>>();
				HashMap<Integer, List<DocumentCategoryDTO>> DOC_CAT_MAP = new HashMap<Integer, List<DocumentCategoryDTO>>();
				HashMap<Integer, String> DOC_TYPE_MAP = new HashMap<Integer, String>();
				DOC_SUBCAT_MAP.put(dscId, ApplicationMaps.DOC_CAT_DOC_SUBCAT_MAP.get(dscId));
				DOC_CAT_MAP.put(dtId, ApplicationMaps.DOC_TYP_DOC_CAT_MAP.get(dtId));
				DOC_TYPE_MAP.put(dtId, ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP.get(dtId));
				modelAndView.addObject("docTypeCatMap", DOC_CAT_MAP);
				modelAndView.addObject("docCatSubCatMap", DOC_SUBCAT_MAP);
				modelAndView.addObject("docTypeMap", DOC_TYPE_MAP);
				
				logger.debug("DOC_SUBCAT_MAP: " + DOC_SUBCAT_MAP);
				logger.debug("DOC_CAT_MAP: " + DOC_CAT_MAP);
			}
			else{
				
			}
		}
		
		
		
		modelAndView.addObject("docTypeMap1", ApplicationMaps.DOCUMENT_TYPE_ID_NAME_MAP);
		modelAndView.addObject("size", ApplicationMaps.DOC_CAT_DOC_SUBCAT_MAP.size());
		return modelAndView;
	*/}
	
	@RequestMapping("/selectCompanyType")
	public ModelAndView selectCompanyType(){
		ModelAndView modelAndView = new ModelAndView("admin/selectCompanyType");
		
		return modelAndView;
	}
	
	@RequestMapping("/mapSuperficialRoles")
	public ModelAndView mapSuperficialRoles(){
		ModelAndView modelAndView = new ModelAndView("admin/mapSuperficialRoles");
		return modelAndView;
	}
	
	@RequestMapping("fetchUserForRole")
	public ModelAndView fetchUserForRole(@RequestParam("formData") String roleId){
		ModelAndView modelAndView = new ModelAndView("admin/fetchUserForRole");
		Set<String> usersList = new HashSet<String>();
		logger.debug("fetching users for Role Id: " + roleId);
		List<UserRoleMappingDTO> userRoleMappingList = authenticationService.fetchUserForRoles(roleId);
		for (UserRoleMappingDTO userRoleMappingDTO : userRoleMappingList) {
			usersList.add(userRoleMappingDTO.getUserId());
		}
		modelAndView.addObject("usersList", usersList);
		modelAndView.addObject("roleId", roleId);
		modelAndView.addObject("roleName", ApplicationMaps.ROLEID_ROLENAME_MAP.get(roleId));
		return modelAndView;
	}
	
	@RequestMapping("fetchUserDetailsForUserId")
	public ModelAndView fetchUserDetailsForUserId(@RequestParam("formData") String formData){
		logger.debug("UserId Selected: " + formData);
		String[] userData = formData.split(",");
		String userName = userData[0];
		String roleId = userData[1];
		
		ModelAndView modelAndView = new ModelAndView("admin/mapBuForSuperFicialRoles");
		
		HashMap<Long, String> locationMap = new HashMap<Long, String>();
		SuperFicialRolesMappingForm superFicialRolesMappingForm = new SuperFicialRolesMappingForm();
		UserDetailsDTO userDetailsDTO = ApplicationMaps.USERID_USER_MAP.get(userName);
		List<LocationDetailsDTO> locationsList = ApplicationMaps.COMPANY_LOC_MAP.get(userDetailsDTO.getCdId());
		for (LocationDetailsDTO locationDetailsDTO : locationsList) {
			locationMap.put(locationDetailsDTO.getLdId(), locationDetailsDTO.getLdName());
		}
		String companyName = ApplicationMaps.COMPANYID_COMPANY_MAP.get(userDetailsDTO.getCdId()).getCdName();
		
		if(ApplicationMaps.SUPERFICIAL_ROLE_MAP_USERID.containsKey(userName + "#" + roleId)){
			List<Long> mappedBUIds =  ApplicationMaps.SUPERFICIAL_ROLE_MAP_USERID.get(userName + "#" + roleId);
			long[] mappedIds = new long[mappedBUIds.size()];
			int counter = 0;
			for(long locId : mappedBUIds){
				mappedIds[counter] = locId;
				counter++;
			}
			superFicialRolesMappingForm.setLdId(mappedIds);
		}
		modelAndView.addObject("companyId", userDetailsDTO.getCdId());
		modelAndView.addObject("userName", userName);
		modelAndView.addObject("roleId", roleId);
		modelAndView.addObject("roleName", ApplicationMaps.ROLEID_ROLENAME_MAP.get(roleId));
		modelAndView.addObject("locationMap", locationMap);
		modelAndView.addObject("companyName", companyName);
		modelAndView.addObject("superFicialRolesMappingForm", superFicialRolesMappingForm);
		
		return modelAndView;
	}
	
	@RequestMapping("saveSuperFicialRoleMappingDetails")
	public void saveSuperFicialRoleMappingDetails(@ModelAttribute SuperFicialRolesMappingForm superFicialRolesMappingForm, HttpServletResponse httpServletResponse){
		
		if(ApplicationMaps.SUPERFICIAL_ROLE_MAP_USERID.containsKey(superFicialRolesMappingForm.getUserId() + "#" + superFicialRolesMappingForm.getRoleId())){
			boolean resultOfDelete = adminService.deletePreviousDataForSuperficialRoleMapping(superFicialRolesMappingForm.getUserId(), superFicialRolesMappingForm.getRoleId());
			if(resultOfDelete)
				logger.debug("PREVIOUS DATA DELETED");
		}
		
		boolean resultOfSave = adminService.saveSuperFicialRoleMappingDetail(superFicialRolesMappingForm);
		logger.debug("resultOfSave" + resultOfSave);
		
		if(resultOfSave){
			try {
				httpServletResponse.getWriter().write("Operation done Successfully");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@InitBinder
	public void binder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, false));
	}

	// for reloading cache
	@RequestMapping(value="rc.htm")
	public ModelAndView reloadCache() {
		
		adminService.reloadCache();
		
		ModelAndView modelAndView = new ModelAndView("cacheReloaded");
		Properties properties = new Properties();
		String url = null;
		try{
			properties.load(AuthenticationController.class.getResourceAsStream("/armory.properties"));
			url = properties.getProperty("reloadCacheUrl");
		}
		catch(Exception e){
			logger.error(e.getMessage(),e);
		}
		
		modelAndView.addObject("redirectUrl", url);
		return modelAndView;
	}

}